<?php
defined('IN_IA') or exit('Access Denied');


class manger {

    public $w = array();
    public $gpc = array();
    public $error;

    public  $pageSize = 20;

    protected $num = array(
        'www.xxx.com'  => 3,
    );

    public function __construct()
    {
        global $_W;
        $basename = pathinfo($_W['siteroot']);
        $number = $this->num[$basename['basename']] ? : 15;
        if (moreOpen()){
            $num = p_getcolumn('multiple', array(), "COUNT(*)");
            if (!p_get('multiple', array('uniacid' => UNIACID))) {
                p_insert('multiple', array('uniacid' => UNIACID, 'created' => time()));
            }
        }

    }
    /**
     * @param $table
     * @param $page
     * @param $where
     * @param string $sequence
     * @param string $desc
     * @return array
     */
    public function getTableList($table, $page, $where, $sequence = 'id', $desc = "DESC")
    {
        $table  = prefix($table, true);
        $page   = max(1, intval($page));
        $list   = p_fetchall('SELECT * FROM '.$table." WHERE {$where} ORDER BY {$sequence} {$desc} LIMIT ".($page - 1) * $this->pageSize.','.$this->pageSize);
        $total  = p_fetchcolumn("SELECT COUNT(*) FROM {$table} WHERE {$where}");
        $pager = pagination($total, $page, $this->pageSize);
        return array(
            'list' => $list,
            'pages' => $pager
        );
    }



    public function getLuckIsPrize($luck_goods_id, $goods_id = 0)
    {
        $data['luck_goods_id'] = $luck_goods_id;
        if ($goods_id) {
            $data['goods_id'] = $goods_id;
        }
        $luckGoodsInfo = p_get('luck_goods_info', $data);

        $luckParticipate = p_get('luck_participate', array('luck_id' => $luckGoodsInfo['luck_id'], 'goods_info_id' => $luckGoodsInfo['id']));

        return $luckParticipate['in_prize'];

    }

    public function cancelLuck($luckId, $goodsId)
    {
        $luckGoodsInfo = p_get('luck_goods_info', array('luck_id' => $luckId, 'id' => $goodsId));
        if (!$luckGoodsInfo){
            return false;
        }
        /*$luckParticipate = p_get('luck_participate', array('goods_info_id' => $luckGoodsInfo['id'], 'luck_id' => $luckId));

        if (!$luckParticipate) {
            return false;
        }*/
        try {
            pdo_begin();
            /*if(!p_update('luck_participate', array('in_prize' => 1, 'goods_info_id' =>0), array('id' => $luckParticipate['id']))){
               throw  new Exception('修改失败');
            }*/
            if(!p_update('luck_goods_info', array('is_appoint' => 1, 'appoint_id' => 0), array('id' => $luckGoodsInfo['id']))){
                throw  new Exception('修改失败');
            }
            pdo_commit();
            return true;
        } catch (Exception $e) {
            pdo_rollback();
            return $e->getMessage();
        }

        return true;
    }

    /**
     * @param   $data     抽奖数据
     * @param   $goods    抽奖商品
     * @param   $id       抽奖id
     * @return  bool
     */
    public function changeLuck($data , $goods , $id)
    {
        if ($id) {
            p_update('luck', $data, array('id' => $id));
            //p_update('luck_goods', $goods, array('luck_id' => $id));
            $luck_goods  = p_get('luck_goods', array('luck_id' => $id));
            //p_delete('luck_goods_info', array('luck_id' => $id));
            $goodInfo = array(
                'luck_id'       => $luck_goods['luck_id'],
                'luck_goods_id' => $luck_goods['id'],
                'name'          => $goods['name'],
                'image'         => $goods['image'],
                'created'       => time()
            );
      /*      for ($i = 0; $i < $goods['number']; $i++) {
                if (!p_insert('luck_goods_info', $goodInfo)) {
                    return false;
                }
            }*/
            return true;
        } else {
            $bool  = p_insert('luck', $data);
            $luck_id = p_insert_id();
            if ($bool){
                $goods['luck_id'] = $luck_id;
                $goods['created'] = time();
                if (p_insert('luck_goods',$goods)) {
                    $luck_goods_id = p_insert_id();
                    $goodInfo = array(
                        'luck_id' => $goods['luck_id'],
                        'luck_goods_id' => $luck_goods_id,
                        'name'  => $goods['name'],
                        'image' => $goods['image'],
                        'created' => $goods['created']
                    );
                    for ($i = 0; $i < $goods['number']; $i++) {
                        if (!p_insert('luck_goods_info', $goodInfo)) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
    }
    /**
     *
     * 一天的时间
     * @param   $date       开始 时间
     * @param   $endDate    结束 时间
     * @param   $filed      字段
     * @return  string
     */
    public function getTime($date ,$endDate, $filed)
    {
        if ($date == $endDate) {
            $state_time = strtotime($date . ' 00:00:01');
            $end_time   = strtotime($endDate . '23:59:59');
        } else {
            $state_time = strtotime($date);
            $end_time   = strtotime($endDate);
        }
        $where = "{$filed} BETWEEN {$state_time} AND {$end_time}";
        return $where ;
    }


    /**
     * 生成夺宝码
     *
     * @param $member_id
     * @param $treasure_id
     * @param $treasure_member_id
     * @param $number
     * @return bool
     */
    public function create_treasure_code($member_id, $treasure_id, $treasure_member_id, $number)
    {
        $data = array(
            'member_id' => $member_id,
            'treasure_id' => $treasure_id,
            'treasure_member_id' => $treasure_member_id,
            'created' => time()
        );
        for ($i = 0; $i < $number; $i++) {
            if (!p_insert('treasure_code', $data)) {
                $this->error = '生成夺宝码失败';
                return false;
            }
            $id = pdo_insertid();
            $no = $id . $treasure_id . $treasure_member_id;
            $content = str_pad($no, 10, '0', STR_PAD_LEFT);

            if (!p_update('treasure_code', array('code' => $content), array('id' => $id))) {
                $this->error = '生成夺宝码失败';
                return false;
            }
        }
        return true;
    }


    /**
     * 开奖
     */
    public function openTreasure($id)
    {
        $treasure = p_get('treasure', array('id' => $id, 'is_delete' => 1, 'is_down' => 1, 'status' => 1));
        if (empty($treasure)) {
            $this->error = '改夺宝不存在或者已经结束';
            return false;
        }
        $code = p_get('treasure_code', array('treasure_id' => $id, 'is_appoint' => 2));
        if (empty($code)) {
            $sql = 'SELECT * FROM ' . prefix('treasure_code') . ' WHERE treasure_id=' . $id . ' ORDER BY RAND()';
            $code = p_fetch($sql);
        }

        pdo_begin();
        try {
            if (!p_update('treasure_code', array('in_prize' => 2), array('id' => $code['id']))) {
                throw new Exception('开奖失败');
            }
            $order = array(
                'member_id' => $code['member_id'],
                'treasure_id' => $id,
                'treasure_code_id' => $code['id'],
                'code' => $code['code'],
                'created' => time()
            );

            if ($treasure['prize_type'] == 2) {
                $goods_fictitious = p_get('goods_fictitious', array('goods_id' => $treasure['id'], 'type' => 3));
                $order['fictitious'] = $goods_fictitious['content'];
                $order['prize_type'] = 2;
                if (!p_update('goods_fictitious', array('status' => 2, 'member_id' => $code['member_id']), array('id' => $goods_fictitious['id'], 'status' => 1))) {
                    throw new Exception('开奖失败');
                }

                $voucher = array(
                    'member_id' => $code['member_id'],
                    'shop_id' => $treasure['shop_id'],
                    'goods_id' => $treasure['id'],
                    'content' => $goods_fictitious['content'],
                    'type' => 3,
                    'created' => time()
                );

                if (!p_insert('my_voucher', $voucher)) {
                    throw new Exception('开奖失败');
                }

            } else {
                $address = p_get('address', array('member_id' => $code['member_id']));
                if (!empty($address)) {
                    $order['name'] = $address['name'];
                    $order['phone'] = $address['phone'];
                    $order['address'] = $address['address'];
                }
            }

            if (!p_insert('treasure_order', $order)) {
                throw new Exception('开奖失败');
            }
            if (!p_update('treasure', array('status' => 2, 'lottery_time' => time()), array('id' => $id))) {
                throw new Exception('开奖失败');
            }
            pdo_commit();
            return true;
        } catch (Exception $e) {
            pdo_rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }
    public function addLuckAssign($luckId, $memberId, $luck_goods_info_id)
    {
        if (empty($luckId) || empty($memberId)) {
            return false;
        }

        $luck = p_get('luck', array('id' => $luckId));
        if (!$luck) {
            return false;
        }
        $luckGoodsInfo = p_get('luck_goods_info', array('is_appoint' =>1, 'luck_id' => $luckId, 'id' => $luck_goods_info_id));
        if (!$luckGoodsInfo) {
            return false;
        }
        $is_member = p_get('luck_participate', array('member_id' => $memberId, 'luck_id' => $luckGoodsInfo['luck_id']));
        /*if (!$is_member || $is_member['in_prize'] == 2) {
            return false;
        }*/
        try {
            pdo_begin();
            /*$luckParticipate = array(
                'goods_info_id' => $luckGoodsInfo['id'],
                'in_prize'      => 2,
            );
            if(!p_update('luck_participate', $luckParticipate, array('luck_id' => $is_member['luck_id'], 'member_id' => $is_member['member_id']))) {
                throw new Exception('修改失败');
            }*/
            $luckGoodsInfoData = array(
                /*'in_member_id'  => $memberId,*/
                'is_appoint'    => 2,
                'appoint_id'    => $is_member['id']
            );
            if(!p_update('luck_goods_info', $luckGoodsInfoData, array('id' => $luckGoodsInfo['id']))){
                throw  new Exception('修改失败');
            }
            pdo_commit();
            return true;
        } catch (Exception $e) {
            pdo_rollback();
            return $e->getMessage();
        }
        return true;
    }

    public function addLuckPeople($luckId, $memberId, $goods_id)
    {
        if (empty($luckId) || empty($memberId)) {
            return false;
        }
        $goods_info = p_get('luck_goods_info', array('goods_id' => $goods_id));
        $luckInfo = p_get('luck', array('id' => $luckId));
        if ($luckInfo['luck_mode'] ==2) {
            $luckGroupId = $this->addLuckGroup($memberId, $luckId, $luckInfo['team_number']);
            if ($luckGroupId == 0) {
                return false;
            }
            return $this->addLuckParticipate($luckId,$memberId, $luckGroupId, $goods_info['id']);
        }
        return $this->addLuckParticipate($luckId,$memberId, '', $goods_info['id']);
    }

    protected function addLuckGroup($memberId, $luckId, $maxNumber)
    {
        if (empty($memberId) || empty($luckId)) {
            return false;
        }
        $data = array(
            'member_id'     => $memberId,
            'luck_id'       => $luckId,
            'max_number'    => $maxNumber,
            'current_number'=> 1,
            'created'       => time()
        );
        if (p_insert('luck_group', $data)){
            return p_insert_id();
        }
        return 0;
    }

    protected function addLuckParticipate($luckId, $memberId, $groupId = '', $luckGoodsInfoId)
    {
        if (empty($memberId) || empty($luckId)) {
            return false;
        }
        $data = array(
            'luck_id'       => $luckId,
            'member_id'     => $memberId,
            'backstage'     => 2,
            'goods_info_id' => $luckGoodsInfoId,
            'created'       => time(),
        );
        if (!empty($groupId)) {
            $data['group_id'] = $groupId;
        }
        if (!p_get('luck_participate', array('luck_id' =>$luckId, 'member_id' => $memberId))) {
            return p_insert('luck_participate', $data);
        }
        return true;
    }


    public function create_luck_code($member_id, $luck_id, $invitation_member_id = 0)
    {
        $data = array(
            'member_id' => $member_id,
            'luck_id' => $luck_id,
            'code' => $this->generate_code($luck_id),
            'created' => time()
        );

        if (!p_insert('luck_code', $data)) {
            $this->error = '生成抽奖码失败';
            return false;
        }

        if ($invitation_member_id > 0
            && $invitation_member_id != $member_id
            && p_get('luck_participate', array('luck_id' => $luck_id, 'member_id' => $invitation_member_id))
        ) {
            $data = array(
                'member_id' => $invitation_member_id,
                'luck_id' => $luck_id,
                'invitation_member_id' => $member_id,
                'type' => 2,
                'code' => $this->generate_code($luck_id),
                'created' => time()
            );
            if (!p_insert('luck_code', $data)) {
                $this->error = '生成抽奖码失败';
                return false;
            }
        }

        return true;
    }

    public function delPhysical($luckId)
    {
        $count = p_getcolumn('luck_goods', array('type' => 1, 'luck_id' => $luckId), 'SUM(number)');
        $luck = p_get('luck', array('id' => $luckId));
        if (p_update('luck', array('prize_number' => $luck['prize_number'] - $count), array('id' => $luckId))){
            if (p_delete('luck_goods', array('type' => 1,'luck_id' => $luckId))){
                return p_delete('luck_goods_info', array('type' => 1,'luck_id' => $luckId));
            }
        }
        return true;

    }

    public function addVoteGoods($id, $goods_name, $goods_image, $number, $type = 1, $fictitious = array(), $redData = array())
    {
        $luck = p_get('luck', array('id' => $id));

        $i = array(
            'luck_id'   => $luck['id'],
            'member_id' => $luck['member_id'],
            'type'      => $type,
            'name'      => $goods_name,
            'image'     => $goods_image,
            'number'    => $number,
            'source'    => 1,
            'created'   => time()
        );

        if ($luck['luck_mode'] == 2 && ($i['number'] % $luck['team_number'] > 0)) {
            $this->error = '奖品数量必须为成团人数的整数倍';
            return false;
        }

        if ($type == 2) {
            $i['number'] = count($fictitious);
            $i['fictitious'] = json_encode($fictitious);
        }

        if ($type ==3) {
            $i['red_type']  = $redData['red_type'];
            $i['red_money'] = $redData['red_money'];
        }

        if (!p_insert('luck_goods', $i)) {
            $this->error = '添加商品失败';
            return false;
        }
        $pid = pdo_insertid();


        if (!p_update('luck', array('prize_number' => $luck['prize_number'] + $i['number']), array('id' => $luck['id']))) {
            $this->error = '添加商品失败';
            return false;
        }

        return $this->createPrize($i, $pid);
    }

    public function createPrize($data, $luck_goods_id)
    {
        $number = $data['number'];
        $red_money = $data['red_money'];
        $red_type = $data['red_type'];
        unset($data['number']);
        unset($data['red_money']);
        unset($data['red_type']);
        $data['luck_goods_id'] = $luck_goods_id;

        if ($data['type'] ==3) {
            if ($red_type == 1) {
                $singe = number_format(($red_money / $number) ,2);
                $data['money'] = $singe;
                for ($i = 0; $i < $number; $i++) {
                    if (!p_insert('luck_goods_info', $data)) {
                        $this->error = '发起失败';
                        return false;
                    }
                }
            } else {
                $singeData = $this->getRedTwo($red_money * 100, $number);
                for ($i = 0; $i < $number; $i++) {
                    $data['money'] = number_format($singeData[$i] / 100, 2);
                    if (!p_insert('luck_goods_info', $data)) {
                        $this->error = '发起失败';
                        return false;
                    }
                }
            }
        }


        if ($data['type'] == 1) {
            for ($i = 0; $i < $number; $i++) {
                if (!p_insert('luck_goods_info', $data)) {
                    $this->error = '发起失败';
                    return false;
                }
            }
        }

        if ($data['type'] == 2) {
            $fictitious = json_decode($data['fictitious']);
            unset($data['fictitious']);
            foreach ($fictitious as $value) {
                $data['fictitious'] = $value;
                if (!p_insert('luck_goods_info', $data)) {
                    $this->error = '发起失败';
                    return false;
                }
            }
        }

        return true;
    }

    public function generate_code($luck_id)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        while (true) {
            for($i=0; $i<10; $i++){
                $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
            }
            if (!p_get('luck_code', array('luck_id' => $luck_id,'invitation_code' => $str))) {
                return $str;
            }
        }
    }


    /**
     *
     * @param $goods_id
     * @return mixed
     */
    public function detail($goods_id)
    {
        $pdd_pid = getConfig('pdd_pid');
        $url = 'http://gw-api.pinduoduo.com/api/router';
        $data = array(
            'type' =>  'pdd.ddk.goods.detail',
            'client_id' => getConfig('pdd_client_id'),
            'timestamp' => time(),
            'p_id' => $pdd_pid,
            'goods_id_list' => '[' . $goods_id . ']'
        );
        $data['sign'] = autograph($data);
        $data = json_decode(http_post($url, $data), true);
        $info = $data['goods_detail_response']['goods_details'][0];
        $info['coupon_start_time'] = date('m月d日', $info['coupon_start_time']);
        $info['coupon_end_time'] = date('m月d日', $info['coupon_end_time']);

        return $info;
    }


    /**
     * 获取用户ids
     * @param $nickname
     * @return bool|string
     */
    public function getMemberId($nickname)
    {
        global $_GPC, $_W;
        $this->gpc = $_GPC;
        $this->w = $_W;
        $table = prefix('member');
        $where = " uniacid = {$this->w['uniacid']} AND nickname LIKE '%{$nickname}%'";
        $member = p_fetchall("SELECT * FROM {$table} WHERE  {$where}");
        if ($member) {
            foreach ($member as $item) {
                $member_id[] = $item['id'];
            }
        }
        if ($member_id) {
            return implode(',', $member_id);
        }
        return false;

    }

    public function getGoodsId($goodsName)
    {
        global $_GPC, $_W;
        $this->gpc = $_GPC;
        $this->w = $_W;
        $table = prefix('goods');
        $where = " uniacid = {$this->w['uniacid']} AND name LIKE '%{$goodsName}%'";
        $member = p_fetchall("SELECT * FROM {$table} WHERE  {$where}");
        if ($member) {
            foreach ($member as $item) {
                $goods_id[] = $item['id'];
            }
        }
        if ($goods_id) {
            return implode(',', $goods_id);
        }
        return false;
    }


    public function getPosters()
    {
        $data = p_get('config', array('key' => 'poster_bg_image'));
        if ($data) {
            return json_decode($data['value'], true);
        }
        return array();
    }


    public function postersHandle($icon, $bg, $color)
    {
        $poster_bg_image = p_get('config', array('key' => 'poster_bg_image'));

        $defaultData = array(array('icon' => $icon,'bg' => $bg, 'color' => $color));

        if (!$poster_bg_image) {
            return p_insert('config', array('key' => 'poster_bg_image', 'value' => json_encode($defaultData)));
        }

        $metadata = json_decode($poster_bg_image['value'], true);
        array_push($metadata, array('icon' => $icon,'bg'   => $bg, 'color' => $color));
        return p_update('config', array('value' => json_encode($metadata)), array('key' => 'poster_bg_image'));

    }

    public function editPosters($key, $behavior)
    {
        $posters = p_get('config', array('key' => 'poster_bg_image'));
        $postersData = json_decode($posters['value'], true);
        if ($behavior == 'delete') {
            unset($postersData[$key]);
            return p_update('config', array('value' => json_encode($postersData)), array('key' => 'poster_bg_image'));
        }
        return $postersData[$key];
    }
    public function editPostersHandle($key, $icon, $bg, $color)
    {
        if(!is_numeric($key)){
            return false;
        }
        $posters = p_get('config', array('key' => 'poster_bg_image'));
        $postersData = json_decode($posters['value'], true);
        $newPosters = $postersData[$key];
        $newPosters['icon'] = $icon;
        $newPosters['bg']   = $bg;
        $newPosters['color'] = $color;
        $postersData[$key] = $newPosters;
        return p_update('config', array('value' => json_encode($postersData)), array('key' => 'poster_bg_image'));
    }


    public function subscribeQueue($activityName, $activityTime, $activityText, $skipUrl, $id = false)
    {
        $data = array(
            'activityName' => $activityName,
            'activityTime' => $activityTime,
            'activityText' => $activityText,
            'skipUrl'       => $skipUrl,

        );
        $queue['content'] = json_encode($data);
        $queue['status']  =1;
        if (!$id) {
            $queue['created'] = time();
        }

        return $id ? p_update('subscribe_queue', $queue, array('id' => $id)) : p_insert('subscribe_queue', $queue);

    }


    /**
     *
     * @param int $total
     * @param int $num
     * @return array
     */
    public function getRedTwo($total = 0 , $num = 0) {
        $bag = [];
        $max = 0;
        for ($i=0; $i < $num - 1; $i++) {
            $_bag = $this->is_repeat($bag, $total);
            if ($_bag > $max) {
                $max = $_bag;
            }
            array_push($bag, $_bag);
        }
        sort($bag);
        $money = [];
        for ($i=0; $i < count($bag); $i++) {
            if ($i == 0) {
                $_money = $bag[$i];
            }else {
                $_money = $bag[$i] - $bag[$i - 1];
            }
            array_push($money, $_money);
        }
        # 最后一个值(max可以不进行比较，在数组排序后 选择$bag[$num-2])
        $_quantity = $total - $max;
        array_push($money, $_quantity);

        return $money;
    }


    protected function is_repeat($array = [] , $max = 0) {
        $_bag = rand(1,$max - 1);
        if (in_array($_bag, $array)) {
            $_bag = $this->is_repeat($array , $max);
        }
        return $_bag;
    }


}